package com.jxtc.enterprise.merchant.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jxtc.enterprise.admin.vo.AdminBillLogVO;
import com.jxtc.enterprise.admin.vo.AdminStoreSettlementDetailVO;
import com.jxtc.enterprise.common.constants.CompanySettlementStatusEnum;
import com.jxtc.enterprise.common.constants.StoreSettlementStatusEnum;
import com.jxtc.enterprise.common.entity.StoreSettlement;
import com.jxtc.enterprise.common.mapper.StoreMapper;
import com.jxtc.enterprise.common.mapper.StoreSettlementMapper;
import com.jxtc.enterprise.common.utils.CurrencyUtil;
import com.jxtc.enterprise.common.utils.Result;
import com.jxtc.enterprise.common.utils.ResultGenerator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 接口 24.xx
 * 商铺端 "数据" Tab页中的 "账单结算"按钮点击后，弹窗页面 相关接口
 */
@RestController
@RequestMapping("/jxtc/enterprise/merchant/settle")
@RequiredArgsConstructor
@Slf4j
public class MerchantSettleController {

    private final StoreMapper storeMapper;
    private final StoreSettlementMapper storeSettlementMapper;

    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为商户营业相关数据；code 为 400 时，message 字段返回错误提示信息，此时 data 字段为空")
    @Operation(summary = "24.1 查看店铺进行中的结算账单个数", tags = "24. 商铺小程序数据页-账单结算", operationId = "24.1")
    @GetMapping("/queryStoreToSolvedSettlementCount")
    public Result<JSONObject> queryStoreToSolvedSettlementCount(@RequestParam("storeId") String storeId, @RequestParam("phone") String phone) {
        log.info("/queryStoreToSolvedSettlementCount, storeid: {}, phone: {}", storeId, phone);

        // 查询商户结算账单表中，未被删除，状态不是 “未结算”
        LambdaQueryWrapper<StoreSettlement> wrapper = new LambdaQueryWrapper<StoreSettlement>()
                .eq(StoreSettlement::getDelFlag, 0)
                .eq(StoreSettlement::getStoreId, storeId)
                .notIn(StoreSettlement::getStatus, StoreSettlementStatusEnum.NOT_SETTLED);
        Long toSolvedSettleCount = storeSettlementMapper.selectCount(wrapper);
        JSONObject resultData = new JSONObject();
        resultData.put("count", toSolvedSettleCount);
        log.info("/queryStoreToSolvedSettlementCount, 接口返回: {}", resultData);
        return ResultGenerator.genSuccessResult(resultData);
    }


    @ApiResponse(responseCode = "200", description = "code 为 200 时，data 字段为商户营业相关数据；code 为 400 时，message 字段返回错误提示信息，此时 data 字段为空")
    @Operation(summary = "24.2 查看结算中的账单详情", tags = "24. 商铺小程序数据页-账单结算", operationId = "24.2")
    @GetMapping("/queryStoreSettlementDetails")
    public Result<JSONArray> queryStoreSettlementDetails(@RequestParam("storeId") String storeId, @RequestParam("phone") String phone) {
        log.info("/queryStoreSettlementDetails, storeid: {}, phone: {}", storeId, phone);

        // 查询商户结算账单表中，未被删除，状态不是 “未结算”
        LambdaQueryWrapper<StoreSettlement> wrapper = new LambdaQueryWrapper<StoreSettlement>()
                .eq(StoreSettlement::getDelFlag, 0)
                .eq(StoreSettlement::getStoreId, storeId)
                .notIn(StoreSettlement::getStatus, StoreSettlementStatusEnum.NOT_SETTLED);
        List<StoreSettlement> storeSettlements = storeSettlementMapper.selectList(wrapper);

        JSONArray toSolvedSettleDetails = new JSONArray();
        for (int i = 0; i < storeSettlements.size(); i++) {
            AdminStoreSettlementDetailVO toSolvedSettleDetail = buildAdminStoreSettlementDetailVO(storeSettlements.get(i));
            toSolvedSettleDetails.add(toSolvedSettleDetail);
        }

        log.info("/queryStoreSettlementDetails, 接口返回: {}", toSolvedSettleDetails);
        return ResultGenerator.genSuccessResult(toSolvedSettleDetails);
    }

    /**
     * 将数据库中查询的数据，封装成返回给前端的数据结构
     * @param storeSettlement
     * @return
     */
    private AdminStoreSettlementDetailVO buildAdminStoreSettlementDetailVO(StoreSettlement storeSettlement) {

        AdminStoreSettlementDetailVO vo = new AdminStoreSettlementDetailVO();
        vo.setSettleId(storeSettlement.getId());

        String billPeriod = String.format("%s ~ %s", storeSettlement.getStartDate(), storeSettlement.getEndDate());
        vo.setBillPeriod(billPeriod);
        vo.setTotalOrderCount(storeSettlement.getTotalOrderCount());

        String orderMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getOrderMoney());
        vo.setOrderMoney(orderMoneyInYuan);

        String additionalMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getAdditionalMoney());
        vo.setAdditionalMoney(additionalMoneyInYuan);

        String deductionMoneyInYuan = CurrencyUtil.fenToYuan(storeSettlement.getDeductionMoney());
        vo.setDeductionMoney(deductionMoneyInYuan);
        // 扣款项取绝对值，避免页面输入的时候输入了负数
        int billTotalMoneyInFen = storeSettlement.getOrderMoney() + storeSettlement.getAdditionalMoney() - Math.abs(storeSettlement.getDeductionMoney());
        String billTotalMoneyInYuan = CurrencyUtil.fenToYuan(billTotalMoneyInFen);
        vo.setBillTotalMoney(billTotalMoneyInYuan);

        List<String> invoiceImages = JSONUtil.toList(storeSettlement.getInvoiceImages(), String.class);
        vo.setInvoiceImages(invoiceImages);

        List<String> transferImages = JSONUtil.toList(storeSettlement.getTransferImages(), String.class);
        vo.setTransferImages(transferImages);

        List<AdminBillLogVO> billLogs = JSONUtil.toList(storeSettlement.getBillLog(), AdminBillLogVO.class);
        vo.setBillLogs(billLogs);

        Integer statusValue = storeSettlement.getStatus();
        vo.setStatusName(CompanySettlementStatusEnum.getNameByValue(statusValue));
        vo.setStatusValue(statusValue);

        return vo;
    }

}
